class Admin::DictionariesController < Admin::PanelController
  def index
    @dictionaries = Dictionary.valid.filter(params).paginate :page => params[:page], :per_page => 30, :order => 'created_at DESC'
    
    respond_to do |format|
      format.html
      format.csv {
        filename = "dictionaries-#{Time.now.strftime("%Y%m%d%H%M%S")}.txt"
        dictionaries = Dictionary.valid.filter(params).all
        send_data(dictionaries.to_csv(:only => [:word], :header => false), :filename => filename)
      }
    end
  end
  
  def show
    @dictionary = Dictionary.find(params[:id])
  end
  
  def new
    @dictionary = Dictionary.new
    @dictionary.flag = 1 unless params[:flag].blank?
  end
  
  def create
    #@dictionary = Dictionary.new(params[:dictionary])
    if params[:words].blank? or params[:words].all?{|w| w.blank? }#@dictionary.save
      flash.now[:error] = "添加词库失败."
      @dictionary = Dictionary.new(params[:dictionary])
      render 'new'
    else
      params[:words].each do |word|
        Dictionary.find_or_create_by_word_and_flag(word, params[:flag].to_i)
      end
      flash[:notice] = "添加词库成功."
      redirect_to params[:save_and_new].blank? ? admin_dictionaries_path : new_admin_dictionary_path
    end
  end
  
  def edit
    @dictionary = Dictionary.find(params[:id])
  end
  
  def update
    @dictionary = Dictionary.find(params[:id])
    if @dictionary.update_attributes(params[:dictionary])
      flash[:notice] = "词库更新成功."
      redirect_to params[:save_and_new].blank? ? edit_admin_dictionary_path(@dictionary) : new_admin_dictionary_path
    else
      render 'edit'
    end
  end
  
  def destroy
    @dictionary = Dictionary.find(params[:id])
    @dictionary.del
    flash[:notice] = "Successfully destroyed dictionary."
    redirect_to admin_dictionaries_url
  end
  
  def update_status
    if params[:ids].blank? or params[:ids].all?{|id| id.blank? }
      flash[:error] = "操作失败."
    else
      status = params[:status].blank? ? 0 : params[:status].to_i
      Dictionary.update_all("status = #{status}", "id IN (#{params[:ids].join(',')})")
      flash[:notice] = "操作成功."
    end
    redirect_to admin_dictionaries_url
  end
  
  def import
    if request.post?
      if Dictionary.import(params[:import_file], params[:flag].to_i)
        flash[:notice] = "词库导入成功."
        redirect_to admin_dictionaries_url
      else
        flash[:error] = "词库导入失败."
        redirect_to import_admin_dictionaries_url
      end
    end
  end
end
